const { mapArrayAttributes } = require('../../utils')
Parse.Cloud.define('getAllMenus', async (req, res) => {
  try {
    const menus = await new Parse.Query('Menu').limit(1000).ascending('seq').find({sessionToken: req.user.getSessionToken()})
    res.success(mapArrayAttributes(menus, ['name', 'path', 'seq'], (result, item) => {
      const parent = item.get('parent')
      const ACL = item.getACL()
      const roles = ACL && ACL.toJSON() || {}
      result.parentId = parent && parent.id
      result.roles = []
      Object.keys(roles).forEach((item) => {
        item.startsWith('role:') && result.roles.push(item.replace('role:', ''))
      })
      return result
    }))
  } catch (err) {
    console.log(err)
    res.error(err.message)
  }
})
